package com.hzp.micromall.auth.entity;

import cn.hutool.core.collection.CollectionUtil;
import com.hzp.micromall.common.core.entity.UserDto;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Author houzipeng
 * @Date 2022/2/10 21:20
 * @Version 1.0
 * 用户认证信息
 */
@Data
public class SecurityUser implements UserDetails {

    /**
     * ID
     */
    private Long id;
    /**
     * 客户端ID
     */
    private String clientId;

    /**
     * 应用内唯一的用户名
     */
    private String username;
    /**
     * 用户的加密后的密码， 不加密会使用前缀
     */
    private String password;
    /**
     * 用户状态
     */
    private Boolean enabled;

    /**
     * 用户的权限集， 默认需要添加前缀
     */
    private Collection<SimpleGrantedAuthority> authorities;

    public SecurityUser(){}

    public SecurityUser(UserDto userDto){
        this.setId(userDto.getId());
        this.setUsername(userDto.getUsername());
        this.setPassword(userDto.getPassword());
        this.setEnabled(userDto.getStatus() == 1);
        this.setClientId(userDto.getClientId());
        if (CollectionUtil.isNotEmpty(userDto.getRoles())) {
            authorities = new ArrayList<>();
            userDto.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
